package com.roc.web.action.excel;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.page.BaseAction;
import com.roc.pojo.Negotiation;
import com.roc.pojo.Operators;
import com.roc.service.IExcelService;
import com.roc.service.IMerchantServices;
import com.roc.service.INegotiationService;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.web.action.negotiation.NegotiationSearchCondition;

@Component
@Scope("prototype")
@Namespace("/excel")
@SuppressWarnings("all")
public class NegotiationExcel extends BaseAction {
	static Logger logger = Logger.getLogger(NegotiationExcel.class);
	@Autowired
	IExcelService excelService;

	@Autowired
	INegotiationService negotiationService;

	@Autowired
	IMerchantServices merchantServices;
	
	@Autowired
	private IPowerInfoService powerInfoService;

	private NegotiationSearchCondition searchCondition;

	private InputStream excelFile;
	private String excelName;

	// 代付流水导出excel
	@Action(value = "negotiationExcel", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xls", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/pages/negotiation/queryNegotiation.jsp") })
	public String EstransExcel() {
		Operators logingMerchant = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);

		String mid = null;
		try {
			if (searchCondition.getMinDate() == null
					|| searchCondition.getMinDate().trim().length() == 0) {
				addActionError("请选择交易起始日期！");
				return ERROR;
			}
			if (!Role.MERCHANT.getCode().equals(logingMerchant.getRoleType())) {// 特约商户
				if (searchCondition.getMerNo() == null
						|| searchCondition.getMerNo().trim().length() == 0) {
					addActionError("请输入商户号码！");
					return ERROR;
				} else {
					mid = searchCondition.getMerNo();
				}

			} else {
				mid = searchCondition.getMerNo();
			}
/*			boolean isTrue = Constance.theDateIsTrue(
					searchCondition.getMinDate(), searchCondition.getMaxDate());
			if (!isTrue) {
				addActionError("您选择的交易日期必须在一个月之内！");
				return ERROR;
			}
*/			
			 Map<String, String> map=powerInfoService.queryRealIdByOpId(logingMerchant.getSuperiorId(), logingMerchant.getRoleType(), logingMerchant.getId(), logingMerchant.getOrgCode());
	           // String orgCode=map.get("orgCode");
	         String superRole= map.get("superRole");
	         String opRealId =map.get("opRealId");
			// 当登录人员为代理商时，查询他的子代理
			searchCondition.setRoleType(superRole);
			if(Role.MERCHANT.getCode().equals(superRole)){
				searchCondition.setMerNo(logingMerchant.getAccountNo());
			}else if(Role.AGENT.getCode().equals(superRole)||Role.SFB_AGENT.getCode().equals(superRole)){
				
				String agentId= opRealId;
				searchCondition.setObj(agentId);
				
			}else if(Role.AGENT_BUSS.getCode().equals(superRole)){
				searchCondition.setOpid(opRealId);
			}else if(Role.MARKET_DIRECT.getCode().equals(superRole) || Role.MARKET_LEAD.getCode().equals(superRole)){
				searchCondition.setMarketorId(opRealId);
			}else if(Role.O_MANAGER.getCode().equals(superRole)){//
				searchCondition.setUcbccdArea(logingMerchant.getOneagentid());
			}/*else if(Role.OPERATORS_COMM.getCode().equals(logingMerchant.getRoleType()) && !Constant.SD_ORG_CD.equals(logingMerchant.getOneagentid())){//运维人员
				searchCondition.setUcbccdArea(logingMerchant.getOneagentid());
			}*/else{
				searchCondition.setOrgCode(logingMerchant.getOrgCode());
			}
			/*if(!Role.SYSTEM.getCode().equals(logingMerchant.getRoleType()))
			{
				searchCondition.setOrgCode(logingMerchant.getOrgCode());
			}*/
			List<Negotiation> date = negotiationService
					.queryByConditions(searchCondition);
			HSSFWorkbook work = excelService.exportNegotiation(date, logingMerchant,
					searchCondition.getConditions());
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			work.write(output);

			byte[] ba = output.toByteArray();
			excelFile = new ByteArrayInputStream(ba);
			output.flush();
			output.close();

		} catch (Exception e) {
			logger.info("######导出Excel失败######");
			addActionError(e.getMessage());
			return ERROR;
		}

		return SUCCESS;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public String getExcelName() {
		String excelName = "代付流水" + Constance.formateDate();

		try {
			excelName = new String(excelName.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			logger.info("生成excel名称失败了！");
		}

		return excelName;

	}

	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}

	public NegotiationSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(NegotiationSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
}
